//
//  HDownloader.m
//  HMusicPlayer
//
//  Created by hament deng on 14/11/6.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HMainDownloader.h"
#import "HCoreConfig.h"
#import "HJAudioPlayer.h"
#import "HSongItem.h"
#import "HPlaylistItem.h"
#import "HMainWC.h"
#import "HSQLManager.h"
#import "GDataXMLNode.h"

@implementation HMainDownloader



+(void)requestLyricWithSongItem:(HSongItem*)songitem
                         server:(NSString*)server
                       subParam:(NSString*)urlPara
                     postStrArr:(NSMutableArray*)postValueArr
            subTheadfinisHandel:(void(^)(BOOL, NSString * lyricpath))finish{

//urlPara, postValueArr 暂时没用到

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        
         NSString * requestPath=@"";
        //歌词迷
        if([server isEqualToString:GECIMIAPISERVER]) {

           
            //根据歌名和演唱者搜索
            if (![songitem.songName isEqualToString:@""] && ![songitem.artist isEqualToString:@""]) {
                
                requestPath=[GECIMIAPISERVER stringByAppendingFormat:@"/%@/%@",songitem.songName,songitem.artist];
            }
            //歌名
            else {
            requestPath=[GECIMIAPISERVER stringByAppendingFormat:@"/%@",songitem.songName];
            }

            
        }
        //
        else if ([server isEqualToString:BAPIWEBSERVER]){
        
            //根据歌名和演唱者搜索
            if (![songitem.songName isEqualToString:@""] && ![songitem.artist isEqualToString:@""]) {
                
                requestPath=[BAPIWEBSERVER stringByAppendingFormat:@"&title=%@$$%@$$$$",songitem.songName,songitem.artist];
            }
            //歌名
            else {
                requestPath=[BAPIWEBSERVER stringByAppendingFormat:@"&title=%@$$",songitem.songName];
            }
        
        
        }

        
        if ([requestPath isEqualToString:@""]) {
            
            finish(NO,nil);
            return ;
        }
        
        debugLog(@"request lyric info url: %@",requestPath);
        NSString * urlString=[requestPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        NSString * urlString=APIDomain;
        NSURL *url = [NSURL URLWithString: urlString];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setTimeoutInterval:20];
        [request setHTTPMethod:@"GET"];
        NSHTTPURLResponse *response;
        NSError *error;
        
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        
        if (returnData &&  !( response.statusCode< 200  ||  response.statusCode>300) ) {

            NSString * lrcpath=nil;
            if([server isEqualToString:GECIMIAPISERVER]) {
            
                lrcpath=[HMainDownloader getLyricPathWithGecimiapi:returnData];
                
            }else if ([server isEqualToString:BAPIWEBSERVER]){
            
                lrcpath=[HMainDownloader getLyricPathWithBWebApi:returnData];
            }
            
            
            if (lrcpath) {
                //如果歌词文件写入成功
                //写入数据库
                [HSQLManager insertSonginfoWithSongItem:songitem andInfo:@{@"lyricsLocalPath":lrcpath}];
                finish(YES,lrcpath);
                return;
            } else {
            
            
                finish(NO,nil);
                return;
            }
            
            
            
            
        } else {
            
            debugLog(@"获取歌词目录失败");
            finish(NO,nil);
            return ;
        }

    
    });



}


//处理歌词迷的返回的api
+(NSString*)getLyricPathWithGecimiapi:(NSData*)data{
    NSString * path=nil;
    
    
    NSDictionary  * dictData=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    
    if (dictData && [dictData isKindOfClass:[NSDictionary class]]) {

        //1.获取count看看
        NSNumber * count=[dictData objectForKey:@"count"];
        
        if (count && count.intValue>0) {
            /*实体类格式 {"aid": 1889264, 
             "lrc": "http://s.geci.me/lrc/210/21070/2107014.lrc",
             "song": "\u6d77\u9614\u5929\u7a7a",
             "artist_id": 8715,
             "sid": 2107014},
            */
            
            NSArray * resArr=[dictData objectForKey:@"result"];
            if(resArr && [resArr isKindOfClass:[NSArray class]] && resArr.count>0 ){
            
                NSDictionary * dic=resArr[0];
               NSString *   requestpath=CHECKSTR(dic[@"lrc"]);

                NSURL *url = [NSURL URLWithString: requestpath];
                //debugLog(@"gecimi lyric upl: %@",requestpath);
                //
                NSString * pathextention=[CHECKSTR([requestpath pathExtension]) lowercaseString];
                if([pathextention isEqualToString:@""]) { pathextention=@"lrc";}
                
                NSHTTPURLResponse *response;
                NSError *error;
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
                [request setTimeoutInterval:20];
                [request setHTTPMethod:@"GET"];
                NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                
                if (returnData &&  !( response.statusCode< 200  ||  response.statusCode>300) ) {
                    //下载成功的话写入sandbox
                    NSString * savePath=[lyricsCache stringByAppendingFormat:@"/%@.%@",[HCoreConfig generateMD5Hash],pathextention];
                    NSError * writeError;
                    //[returnData writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:&writeError];
                    [returnData writeToFile:savePath  atomically:YES];
                    if (!writeError) {
                        path=savePath;
                    }

                }else {
                
               
                
                }
                
                
            }
            
        }
        
    }

 return path;
}

//处理bwebserver的返回的api
+(NSString*)getLyricPathWithBWebApi:(NSData*)data{

    NSString * path=nil;
    
    NSError * pasererror;
    GDataXMLDocument * document=[[GDataXMLDocument alloc] initWithData:data options:1 error:&pasererror] ;

    if (document) {
        //http://box.zhangmen.baidu.com/x?op=12&count=1&title=%E7%AC%AC%E5%87%A0%E5%A4%A9$$%E9%BB%84%E5%AE%97%E6%B3%BD$$$$
        //获取歌词ID
        NSString *nameXpath1=[NSString stringWithFormat:@"//result/url/lrcid"];
        NSArray * resArr=[document nodesForXPath:nameXpath1 error:nil];
            if(resArr.count>0){
                GDataXMLElement * stockElement=resArr[0];
                NSString * lyricID=[stockElement stringValue];
                lyricID=CHECKSTR(lyricID);
                if (![lyricID isEqualToString:@""] && ![lyricID isEqualToString:@"0"]) {

                NSString* requestpath=[NSString stringWithFormat:@"http://box.zhangmen.baidu.com/bdlrc/%d/%@.lrc",lyricID.intValue/100,lyricID];

                NSURL *url = [NSURL URLWithString: requestpath];
                debugLog(@"bwebapi lyric upl: %@",requestpath);
                //
                NSString * pathextention=@"lrc";
   
                NSHTTPURLResponse *response;
                NSError *error;
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
                [request setTimeoutInterval:20];
                [request setHTTPMethod:@"GET"];
                NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                
                if (returnData &&  !( response.statusCode< 200  ||  response.statusCode>300) ) {
                    //下载成功的话写入sandbox
                    NSString * savePath=[lyricsCache stringByAppendingFormat:@"/%@.%@",[HCoreConfig generateMD5Hash],pathextention];
                    NSError * writeError;
                    //[returnData writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:&writeError];
                    [returnData writeToFile:savePath  atomically:YES];
                    if (!writeError) {
                        path=savePath;
                    }
                    
                }
               }
                
            }
            
        
        
    }
    
    return path;
}


@end
